package com.cmw.core.security.certificate;

import java.util.Map;

public class RSATester {
	  static String publicKey;  
	    static String privateKey;  
	  
	    static {  
	        try {  
	            Map<String, Object> keyMap = CmwRSA.genKeyPair();  
	            publicKey = CmwRSA.getPublicKey(keyMap);  
	            privateKey = CmwRSA.getPrivateKey(keyMap);  
	            System.err.println("公钥: \n\r" + publicKey);  
	            System.err.println("私钥： \n\r" + privateKey);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  
	      
	    public static void main(String[] args) throws Exception {  
	        test();  
	      //  testSign();  
	    }  
	  
	    static void test() throws Exception {  
	        System.err.println("公钥加密——私钥解密");  
	        String source = "SubSystemLicense = FINTER_A0001FINTER_A0001FINTER_A0001;小额贷款业务管理系统小额贷款业务管理系统;500000";  
	        System.out.println("\r加密前文字：\r\n" + source);  
	        byte[] data = source.getBytes();
	        byte[] encodedData = CmwRSA.encryptByPublicKey(data, publicKey);
	     
//	        System.out.println("加密后文字：\r\n" + new String(encodedData));  
//	        byte[] decodedData = CmwRSA.decryptByPrivateKey(encodedData, privateKey);  
//	        String target = new String(decodedData);  
//	        System.out.println("解密后文字: \r\n" + target);
	        
	        String hex_encodedData = DigitalTransHandler.byte2hex(encodedData);
	        System.out.println("---------- HEX 加密字符串 --------");
	        System.out.println(hex_encodedData);
	        System.out.println("---------- HEX 解密字符串 --------");
	        byte[] byte_edata = DigitalTransHandler.hex2byte(hex_encodedData);
	        byte[] edatas = CmwRSA.decryptByPrivateKey(byte_edata, privateKey);
	        String de_str = new String(edatas);
	        System.out.println(de_str);
	    }  
	  
	    static void testSign() throws Exception {  
	        System.err.println("私钥加密——公钥解密");  
	        String source = "这是一行测试RSA数字签名的无意义文字";  
	        System.out.println("原文字：\r\n" + source);  
	        byte[] data = source.getBytes();  
	        byte[] encodedData = CmwRSA.encryptByPrivateKey(data, privateKey);  
	        System.out.println("加密后：\r\n" + new String(encodedData));  
	        byte[] decodedData = CmwRSA.decryptByPublicKey(encodedData, publicKey);  
	        String target = new String(decodedData);  
	        System.out.println("解密后: \r\n" + target);  
	        System.err.println("私钥签名——公钥验证签名");  
	        String sign = CmwRSA.sign(encodedData, privateKey);  
	        System.err.println("签名:\r" + sign);  
	        boolean status = CmwRSA.verify(encodedData, publicKey, sign);  
	        System.err.println("验证结果:\r" + status);  
	    }  
}
